﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Security.Cryptography;

namespace SD.Common.Utilities
{
    public class Connector
    {
        private static string connectstring = "";
        private static string key = "minhdung";
        public static String EncryptConString(String str)
        {            
            try
            {
                byte[] keyArr;
                byte[] EnCryptArr = UTF8Encoding.UTF8.GetBytes(str);
                MD5CryptoServiceProvider md5Hash = new MD5CryptoServiceProvider();
                keyArr = md5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider();
                tripDes.Key = keyArr;
                tripDes.Mode = CipherMode.ECB;
                tripDes.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = tripDes.CreateEncryptor();
                byte[] arrResult = transform.TransformFinalBlock(EnCryptArr, 0, EnCryptArr.Length);
                connectstring = Convert.ToBase64String(arrResult, 0, arrResult.Length);
                return connectstring;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return connectstring;
        }

        public static String DecryptConString(String str)
        {

            try
            {
                byte[] keyArr;
                byte[] DeCryptArr = Convert.FromBase64String(str);
                MD5CryptoServiceProvider MD5Hash = new MD5CryptoServiceProvider();
                keyArr = MD5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider();
                tripDes.Key = keyArr;
                tripDes.Mode = CipherMode.ECB;
                tripDes.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = tripDes.CreateDecryptor();
                byte[] arrResult = transform.TransformFinalBlock(DeCryptArr, 0, DeCryptArr.Length);
                connectstring = UTF8Encoding.UTF8.GetString(arrResult);
                return connectstring;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return connectstring;
        }

        public static SqlConnection GetConnection()
        {
            try
            {
                String strConnection = DecryptConString((String)ConfigurationSettings.AppSettings["ConnectionString"]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return new SqlConnection(connectstring);
        }
    }
}
